﻿using System;
using System.Collections.Generic;
using System.Linq;
using SD.LLBLGen.Pro.ORMSupportClasses;
using SD.LLBLGen.Pro.LinqSupportClasses;
using Northwinddemo.BusinessLayer.Repository.Abstract;
using Northwinddemo.DAL.EntityClasses;
using Northwinddemo.DAL.DatabaseSpecific;
using Northwinddemo.DAL.Linq;
using MvcContrib.Pagination;
using System.Collections.Specialized;
using BaseBL;
using xVal.ServerSide;

namespace Northwinddemo.BusinessLayer.Repository.Concrete
{
    public class ProductsRepository : NortwindRepository<ProductsEntity>, IProductsRepository
    {

        public override ProductsEntity GetById(int productId, IDataAccessAdapter adapter)
        {
            return (from p in new LinqMetaData(adapter).Products
                    where p.ProductId == productId
                    select p).Single();
        }

        public override IList<ProductsEntity> GetAll(IDataAccessAdapter adapter)
        {
            throw new NotImplementedException();
        }

        public IPagination<ProductsEntity> GetBySearchOrderByProductNamePrefetchSupplierAndCategory(string search, int? page)
        {
            using (DataAccessAdapter adapter = new DataAccessAdapter())
            {
                var products = (from p in new LinqMetaData(adapter).Products
                                where p.ProductName.Contains(search)
                                orderby p.ProductName
                                select p).
                                WithPath(p => p.Prefetch(s => s.Suppliers).
                                                Prefetch(c => c.Categories)).
                                AsPagination(page ?? 1, 10);
                var totalPages = products.TotalPages; // This line will cause immediate loading from DB instead of default lazy loading.
                return products;
            }
        }

    }
}
